package com.cat.chapter035;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author cat
 * @description https://leetcode.cn/problems/insert-delete-getrandom-o1/description/
 * @create 2025/5/30 21:29
 * @since JDK17
 */

public class Code03LC380 {
    HashMap<Integer, Integer> map;
    ArrayList<Integer> list;
    public Code03LC380() {
        map = new HashMap<>();
        list = new ArrayList<>();
    }

    public boolean insert(int val) {
        if (map.containsKey(val)) return false;
        map.put(val, list.size());
        list.add(val);
        return true;
    }

    public boolean remove(int val) {
        if (!map.containsKey(val)) return false;
        Integer idx = map.get(val);
        Integer last = list.get(list.size() - 1);
        list.set(idx, last);
        map.put(last, idx);
        list.remove(list.size() - 1);
        map.remove(val);
        return true;
    }

    public int getRandom() {
        return list.get(((int) (Math.random() * list.size())));
    }

}
